import 'package:flutter/cupertino.dart';
import 'package:flutter_app/common/apis/apis.dart';
import 'package:flutter_app/common/dto/dto.dart';
import 'package:flutter_app/common/model/model.dart';
import 'package:flutter_app/common/routes/app_pages.dart';
import 'package:flutter_app/common/widgets/captcha/captcha.dart';
import 'package:flutter_app/common/widgets/toast.dart';
import 'package:get/get.dart';
import 'package:flutter_app/common/utils/utils.dart';
import 'state.dart';
import 'package:flutter_app/global.dart';

class SignInLogic extends GetxController {
  final state = SignInState();

  // 登录请求 获取token 、用户信息，并将其持久化
  _login(LoginRequest params) async {
    LoginResponse loginResponse = await UserAPI.login(params: params);
    if(loginResponse.success){
      // TOKEN信息持久化
      Global.saveToken(loginResponse.data);
      // 通过token获取用户信息
      LoginUserResponse loginUserResponse = await UserAPI.getLoginUser();
      if(loginUserResponse.success){
        // 持久化用户信息
        Global.saveLoginUserInfo(User(
          name: loginUserResponse.data?.name,
          avatar:loginUserResponse.data?.avatar,
          // birthday:loginUserResponse.data?.birthday,
          sex:loginUserResponse.data?.sex,
          phone:loginUserResponse.data?.phone,
        ));
      }else{
        Get.snackbar("提示", loginResponse.message);
      }
      // 页面进行跳转
      Get.offAllNamed(AppRoutes.Application);
      // Get.toNamed(AppRoutes.Application);
    }else{
      Get.snackbar("提示", loginResponse.message);
    }
  }


  // 执行登录操作
  confirm(BuildContext context) async {
    // if (!duIsEmail((state.accountController.value.text))) {
    //   toastInfo(msg: '请正确输入邮件');
    //   return;
    // }
    if (!duCheckStringLength(state.passController.value.text, 6)) {
      toastInfo(msg: '密码不能小于6位');
      return;
    }
    // 登录请求参数
    LoginRequest params = LoginRequest(
      account: state.accountController.value.text,
      password: state.passController.value.text, // password: duSHA256(state.passController.value.text),
    );
    CaptchaOpenResponse captchaOpenResponse = await UserAPI.getCaptchaOpen();
    if(captchaOpenResponse.success && captchaOpenResponse.data){
      loadingClickWord(context,
          onSuccess: (v) async {
            // 为登录请求参数添加验证码
            params.code = v;
            _login(params);
          },
          onFail: (){
          }
      );
    }else{
      _login(params);
    }
  }

  // 跳转 注册界面
  handleNavSignUp() {
    Get.toNamed(AppRoutes.SIGN_UP);
  }

}
